using aichat.Entities;
using aichat.Services;
using Prism.Commands;
using Prism.Mvvm;
using System.Collections.ObjectModel;
using System.Windows;

namespace aichat.ViewModels
{
    public class VipViewModel : BindableBase
    {
        private readonly IPaymentService _paymentService;
        private readonly IUserService _userService;
        private readonly int _currentUserId;

        public VipViewModel(IPaymentService paymentService, IUserService userService, int currentUserId)
        {
            _paymentService = paymentService;
            _userService = userService;
            _currentUserId = currentUserId;

            PurchaseVipCommand = new DelegateCommand<VipType>(PurchaseVip);
            ViewPaymentHistoryCommand = new DelegateCommand(ViewPaymentHistory);

            VipPlans = new ObservableCollection<VipPlanInfo>();
            PaymentHistory = new ObservableCollection<PaymentRecord>();

            LoadVipPlans();
            LoadUserInfo();
            LoadPaymentHistory();
        }

        private UserModel? _currentUser;
        public UserModel? CurrentUser
        {
            get => _currentUser;
            set => SetProperty(ref _currentUser, value);
        }

        private bool _isVip = false;
        public bool IsVip
        {
            get => _isVip;
            set => SetProperty(ref _isVip, value);
        }

        private string _vipStatus = string.Empty;
        public string VipStatus
        {
            get => _vipStatus;
            set => SetProperty(ref _vipStatus, value);
        }

        private int _dailyChatCount = 0;
        public int DailyChatCount
        {
            get => _dailyChatCount;
            set => SetProperty(ref _dailyChatCount, value);
        }

        private int _maxDailyChats = 20;
        public int MaxDailyChats
        {
            get => _maxDailyChats;
            set => SetProperty(ref _maxDailyChats, value);
        }

        public ObservableCollection<VipPlanInfo> VipPlans { get; }
        public ObservableCollection<PaymentRecord> PaymentHistory { get; }

        public DelegateCommand<VipType> PurchaseVipCommand { get; }
        public DelegateCommand ViewPaymentHistoryCommand { get; }

        private async void LoadVipPlans()
        {
            VipPlans.Clear();

            var monthlyPrice = await _paymentService.GetVipPriceAsync(VipType.Monthly);
            var yearlyPrice = await _paymentService.GetVipPriceAsync(VipType.Yearly);
            var permanentPrice = await _paymentService.GetVipPriceAsync(VipType.Permanent);

            VipPlans.Add(new VipPlanInfo
            {
                Type = VipType.Monthly,
                Name = "月度会员",
                Price = monthlyPrice,
                Description = "每月无限次对话，享受所有AI模型",
                Features = new[] { "无限次对话", "所有AI模型", "优先响应" }
            });

            VipPlans.Add(new VipPlanInfo
            {
                Type = VipType.Yearly,
                Name = "年度会员",
                Price = yearlyPrice,
                Description = "每年无限次对话，享受所有AI模型，更优惠",
                Features = new[] { "无限次对话", "所有AI模型", "优先响应", "年度优惠" }
            });

            VipPlans.Add(new VipPlanInfo
            {
                Type = VipType.Permanent,
                Name = "永久会员",
                Price = permanentPrice,
                Description = "永久无限次对话，享受所有AI模型",
                Features = new[] { "无限次对话", "所有AI模型", "优先响应", "永久有效" }
            });
        }

        private async void LoadUserInfo()
        {
            CurrentUser = await _userService.GetUserByIdAsync(_currentUserId);
            if (CurrentUser != null)
            {
                IsVip = await _userService.IsVipUserAsync(_currentUserId);
                DailyChatCount = CurrentUser.DailyChatCount;
                
                UpdateVipStatus();
            }
        }

        private void UpdateVipStatus()
        {
            if (CurrentUser == null) return;

            if (IsVip)
            {
                if (CurrentUser.VipType == VipType.Permanent)
                {
                    VipStatus = "永久VIP会员";
                }
                else if (CurrentUser.VipExpireDate.HasValue)
                {
                    VipStatus = $"VIP会员 - 到期时间: {CurrentUser.VipExpireDate.Value:yyyy-MM-dd}";
                }
            }
            else
            {
                VipStatus = $"普通用户 - 今日已使用 {DailyChatCount}/{MaxDailyChats} 次";
            }
        }

        private async void LoadPaymentHistory()
        {
            try
            {
                var history = await _paymentService.GetUserPaymentsAsync(_currentUserId);
                
                PaymentHistory.Clear();
                foreach (var payment in history)
                {
                    PaymentHistory.Add(payment);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载支付历史失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void PurchaseVip(VipType vipType)
        {
            try
            {
                var payment = await _paymentService.CreatePaymentAsync(_currentUserId, vipType, "Alipay");
                
                // 生成支付宝支付URL
                var paymentUrl = await _paymentService.GenerateAlipayUrlAsync(payment);
                
                // 这里应该打开支付页面或显示支付二维码
                MessageBox.Show($"订单已创建，订单号: {payment.OrderId}\n支付金额: ¥{payment.Amount}\n请完成支付", 
                    "支付信息", MessageBoxButton.OK, MessageBoxImage.Information);
                
                // 模拟支付成功（实际应用中应该通过回调处理）
                // await _paymentService.ProcessPaymentAsync(payment.OrderId, "MOCK_TRANSACTION_ID");
                
                // 重新加载用户信息
                LoadUserInfo();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建支付订单失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ViewPaymentHistory()
        {
            // 这里可以打开支付历史详情窗口
            MessageBox.Show($"您共有 {PaymentHistory.Count} 条支付记录", "支付历史", MessageBoxButton.OK, MessageBoxImage.Information);
        }
    }

    public class VipPlanInfo
    {
        public VipType Type { get; set; }
        public string Name { get; set; } = string.Empty;
        public decimal Price { get; set; }
        public string Description { get; set; } = string.Empty;
        public string[] Features { get; set; } = Array.Empty<string>();
    }
} 